<?php
/**
 * Created by PhpStorm.
 * User: wodrow
 * Date: 18-3-9
 * Time: 上午11:00
 */

namespace console\modules\bank\controllers;


use common\components\bank\Icbc;
use common\components\tools\Api;
use common\components\tools\Tools;
use common\models\BankBackSendLog;
use common\models\BankGuaranteeCompanyBind;
use common\models\Custom;
use common\models\FileListDownloadLog;
use common\models\FileListInfo;
use yii\base\ErrorException;
use yii\console\Controller;
use common\models\FileListNotice;

class BusiController extends Controller
{
    /**
     * 根据通知下载文件列表
     * php yii bank/busi/file-list-download
     */
    public function actionFileListDownload()
    {
        $notices = FileListNotice::find()->where(['status'=>FileListNotice::STATUS_DEFAULT])->all();
        $trans = \Yii::$app->db->beginTransaction();
        try{
            foreach($notices as $k => $v){
                $notice = $v;
                $x['pub']['platno'] = substr($v->filesrc, 0, 4);
                $x['pub']['assurerno'] = $v->assurerno;
                $x['req']['filetype'] = $v->filetype;
                $x['req']['filesrc'] = $v->filesrc;
                $x['req']['datadt'] = $v->datadt;
                $cache_key = 'file_list_download_icbc_'.$v->assurerno;
                $icbc = \Yii::$app->cache->get($cache_key);
                if (!$icbc){
                    $bind = BankGuaranteeCompanyBind::findOne(['assurerno' => $v->assurerno]);
                    $icbc = new Icbc();
                    $icbc->instance = $bind;
                    \Yii::$app->cache->set($cache_key, $icbc, 3600);
                }
                $_back = $icbc->downloadFileList($x);
                $download_log = new FileListDownloadLog();
                $download_log->created_at = time();
                $download_log->file_list_notice_id = $v->id;
                if ($_back){
                    $download_log->is_success = $download_log::IS_SUCCESS_TRUE;
                    $download_log->back_detail = serialize($_back);
                    $notice->status = $notice::STATUS_SUCCESS;
                }else{
                    $download_log->is_success = $download_log::IS_SUCCESS_FALSE;
                    $notice->status = $notice::STATUS_FAILED;
                }
                foreach ($_back as $k1 => $v1){
                    if (isset($v1['detail'])){
                        $detail = $v1['detail'];
                        $info = FileListInfo::findOne([
                            'notice_id' => $v->id,
                            'type' => $v->filetype,
                            'card_no' => $detail['卡号'],
                            'name' => $detail['姓名'],
                            'cert_type' => $detail['证件类型'],
                            'cert_no' => $detail['证件号码'],
                        ]);
                        if (!$info){
                            $info = new FileListInfo();
                            $info->notice_id = $v->id;
                            $info->type = $v->filetype;
                            $info->card_no = $detail['卡号'];
                            $info->name = $detail['姓名'];
                            $info->cert_type = $detail['证件类型'];
                            $info->cert_no = $detail['证件号码'];
                        }
                        $orderno = $detail['订单号'];
                        if ($orderno){
                            $custom = Custom::getByOrderno($orderno);
                            $info->custom_id = $custom->id;
                        }
                        $info->area_no = $detail['地区号'];
                        $info->plat_no = $detail['平台编号'];
                        $info->guaranty_unit_no  = $detail['担保单位编号'];
                        if (isset($detail['发卡标识']))$info->card_issue_mark = $detail['发卡标识'];
                        if (isset($detail['对账单日']))$info->reconciliation_at = $detail['对账单日'];
                        if (isset($detail['还款日']))$info->repayment_at = $detail['还款日'];
                        if (isset($detail['数据日期']))$info->data_date = $detail['数据日期'];
                        if (isset($detail['卡余额']))$info->card_balance = $detail['卡余额'];
                        if (isset($detail['最优还款额']))$info->optimal_repayment_amout = $detail['最优还款额'];
                        if (isset($detail['累计违约次数']))$info->cumulative_break_contract_times = $detail['累计违约次数'];
                        if (isset($detail['连续违约次数']))$info->continuity_break_contract_times = $detail['连续违约次数'];
                        if (isset($detail['经办支行']))$info->run_branch = $detail['经办支行'];
                        if (isset($detail['分期业务种类']))$info->instalment_type = $detail['分期业务种类'];
                        if (isset($detail['分期金额']))$info->instalment_amount = $detail['分期金额']*100;
                        if (isset($detail['汇总笔数']))$info->gather_times = $detail['汇总笔数'];
                        if (isset($detail['汇总金额']))$info->gather_amount = $detail['汇总金额']*100;
                        if (isset($detail['催缴情况']))$info->ugry_pay_situation = $detail['催缴情况'];
                        $other_data = $detail;
                        $info->other_data = serialize($other_data);
                        if (!$info->save()){
                            throw new ErrorException(Tools::makeModelGetErrorsToStringAndGetIt($info));
                        }
                    }
                }
                if (!$download_log->save()){
                    throw new ErrorException(Tools::makeModelGetErrorsToStringAndGetIt($download_log));
                }
                if (!$notice->save()){
                    throw new ErrorException(Tools::makeModelGetErrorsToStringAndGetIt($notice));
                }
            }
            $trans->commit();
        }catch (ErrorException $e){
            $trans->rollBack();
            throw $e;
        }
    }

    /**
     * php yii bank/busi/inquiry-apply-rate
     * @param $orderno
     */
    public function actionInquiryApplyRate($orderno)
    {
        $data = [
            'orderno' => $orderno,
        ];
        $resp = Api::request("/bank/business/inquiry-apply-rate", $data);
        var_dump($resp->content);exit;
    }

    /**
     * php yii bank/busi/inquery-special-card
     * @param $orderno
     */
    public function actionInquerySpecialCard($orderno)
    {
        $data = [
            'orderno' => $orderno,
        ];
        $resp = Api::request("/bank/business/inquery-special-card-schedule", $data);
        var_dump($resp->content);exit;
    }

    /**
     * php yii bank/busi/resend-credit-by-log
     */
    public function actionResendCreditByLog()
    {
        /**
         * @var BankBackSendLog[] $bank_back_logs
         */
        $bank_back_logs = BankBackSendLog::find()->where(['>', 'time', 1534953600])->andWhere(['<', 'time', 1535040000])->all();
        foreach ($bank_back_logs as $k => $v){
            $req_data = unserialize($v->request_data);
            $req_params = json_decode($req_data['reqparam'], true);
            if ($req_params['req']['result'] == '099'){
                if (!$v->creditOrderLog->app_post_data){
                    echo "credit_order_log:";
                    var_dump($v->creditOrderLog->id);exit;
                }
                $app_post_data = unserialize($v->creditOrderLog->app_post_data);
                unset($app_post_data['s']);
                $resp = Api::request('/bank/business/submit-credit', $app_post_data);
                $resp_arr = json_decode($resp->content, true);
                if ($resp_arr['code'] == 200){
                    var_dump($resp_arr);
                }else{
                    echo "error:{$v->creditOrderLog->id}";
                    var_dump($resp_arr);exit;
                }
            }
        }
    }
}